/**
 * 统一API服务
 * 封装所有后端API调用，提供类型安全的接口
 */

import {
  httpGet,
  httpPost,
  httpPut,
  httpDelete,
  httpUpload,
} from "../utils/http";
import { API_ENDPOINTS } from "../config/env";

// 认证相关API
export const authAPI = {
  // 用户登录
  login: async (data: { phone: string; password: string; type: string }) => {
    try {
      console.log("🔐 调用登录API:", {
        endpoint: API_ENDPOINTS.AUTH.LOGIN,
        data: { ...data, password: "***" }, // 隐藏密码
      });

      const response = await httpPost(API_ENDPOINTS.AUTH.LOGIN, data);

      console.log("✅ 登录响应:", {
        code: response?.code,
        message: response?.msg,
        hasToken: !!response?.data?.token,
        hasUserInfo: !!response?.data?.userInfo,
      });

      return response;
    } catch (error) {
      console.error("❌ 登录失败:", error);
      throw error;
    }
  },

  // 用户注册
  register: async (data: {
    phone: string;
    password: string;
    name: string;
    code: string;
    type: string;
    email?: string;
    headImg?: string;
    // 教师字段
    department?: string;
    title?: string;
    subject?: string;
    // 学生字段
    studentId?: string;
    major?: string;
    className?: string;
    grade?: string;
  }) => {
    try {
      console.log("📝 调用注册API:", {
        endpoint: API_ENDPOINTS.AUTH.REGISTER,
        data: { ...data, password: "***" }, // 隐藏密码
      });

      const response = await httpPost(API_ENDPOINTS.AUTH.REGISTER, data);

      console.log("✅ 注册响应:", {
        code: response?.code,
        message: response?.msg,
      });

      return response;
    } catch (error) {
      console.error("❌ 注册失败:", error);
      throw error;
    }
  },

  // 发送验证码
  sendCode: async (phone: string, captcha: string) => {
    try {
      console.log("📱 发送验证码:", {
        endpoint: API_ENDPOINTS.AUTH.SEND_CODE,
        phone,
        captcha,
      });

      const response = await httpPost(API_ENDPOINTS.AUTH.SEND_CODE, {
        phone,
        captcha,
      });

      console.log("✅ 验证码响应:", {
        code: response?.code,
        message: response?.msg,
      });

      return response;
    } catch (error) {
      console.error("❌ 发送验证码失败:", error);
      throw error;
    }
  },

  // 获取用户信息
  getUserInfo: async () => {
    try {
      console.log("👤 获取用户信息:", {
        endpoint: API_ENDPOINTS.AUTH.USER_INFO,
      });

      const response = await httpGet(API_ENDPOINTS.AUTH.USER_INFO);

      console.log("✅ 用户信息响应:", {
        code: response?.code,
        hasUserInfo: !!response?.data,
      });

      return response;
    } catch (error) {
      console.error("❌ 获取用户信息失败:", error);
      throw error;
    }
  },

  // 用户登出
  logout: async () => {
    try {
      console.log("🚪 调用登出API:", { endpoint: API_ENDPOINTS.AUTH.LOGOUT });

      const response = await httpPost(API_ENDPOINTS.AUTH.LOGOUT);

      console.log("✅ 登出响应:", { code: response?.code });

      return response;
    } catch (error) {
      console.error("❌ 登出失败:", error);
      throw error;
    }
  },

  // 获取图形验证码
  getCaptcha: () => httpGet("/api/v1/user/notify"),
};

// AI相关API - 重构为调用Python AI服务
export const aiAPI = {
  // 获取默认用户信息
  getDefaultUserInfo: () => {
    try {
      const userStr = localStorage.getItem('user');
      const user = userStr ? JSON.parse(userStr) : null;
      return {
        account_id: user?.id?.toString() || "default_user",
        course_id: user?.currentCourseId?.toString() || "default_course"
      };
    } catch (error) {
      console.warn("获取用户信息失败，使用默认值", error);
      return {
        account_id: "default_user",
        course_id: "default_course"
      };
    }
  },

  // 普通聊天 - 调用Python AI服务
  chat: async (message: string) => {
    const userInfo = aiAPI.getDefaultUserInfo();
    
    const response = await fetch("http://localhost:8000/api/teach/chat", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        message,
        account_id: userInfo.account_id,
        course_id: userInfo.course_id,
      }),
    });

    if (!response.ok) {
      throw new Error(`AI聊天失败: ${response.status}`);
    }

    // 处理流式响应
    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error("无法获取响应流");
    }

    let fullResponse = "";
    const decoder = new TextDecoder();

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      
      const chunk = decoder.decode(value);
      fullResponse += chunk;
    }

    return { reply: fullResponse || "AI服务暂时无响应" };
  },

  // 流式聊天 - 直接返回Response对象
  streamChat: async (message: string) => {
    const userInfo = aiAPI.getDefaultUserInfo();
    
    return fetch("http://localhost:8000/api/teach/chat", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        message,
        account_id: userInfo.account_id,
        course_id: userInfo.course_id,
      }),
    });
  },

  // AI生成题目 - 使用文件接口
  generateQuestions: async (prompt: string) => {
    try {
      const formData = new FormData();
      const blob = new Blob([prompt], { type: 'text/plain' });
      formData.append('file', blob, 'question_prompt.txt');
      formData.append('knowledge_point', prompt);

      const response = await fetch("http://localhost:8000/api/file/exam", {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("生成题目失败");
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("无法获取响应流");
      }

      let questionsJson = "";
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        questionsJson += chunk;
      }

      try {
        const questions = JSON.parse(questionsJson);
        return { questions };
      } catch (parseError) {
        console.warn("解析题目JSON失败，返回原始文本", parseError);
        return { questions: questionsJson };
      }
    } catch (error) {
      console.error("AI生成题目失败:", error);
      throw error;
    }
  },

  // AI分析 - 使用评论接口
  analyze: async (data: any) => {
    try {
      const analysisPrompt = `请分析以下数据：\n\n${JSON.stringify(data, null, 2)}\n\n请提供专业的分析报告和建议。`;

      const response = await fetch("http://localhost:8000/api/teach/comment", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ comments: analysisPrompt }),
      });

      if (!response.ok) {
        throw new Error("AI分析失败");
      }

      const result = await response.json();
      return result;
    } catch (error) {
      console.error("AI分析失败:", error);
      throw error;
    }
  },

  // 生成文件大纲
  generateOutline: async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);

    return fetch("http://localhost:8000/api/file/outline", {
      method: "POST",
      body: formData,
    });
  },

  // 生成PPT
  generatePPT: async (file: File, pages: number = 3) => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('pages', pages.toString());

    const response = await fetch("http://localhost:8000/api/file/ppt", {
      method: "POST",
      body: formData,
    });

    if (!response.ok) {
      throw new Error("生成PPT失败");
    }

    return await response.blob();
  },

  // 文件处理
  processFile: async (file: File, courseId?: string, fileId?: string) => {
    const formData = new FormData();
    formData.append('file', file);
    if (courseId) formData.append('course_id', courseId);
    if (fileId) formData.append('file_id', fileId);

    const response = await fetch("http://localhost:8000/api/teach/upload", {
      method: "POST",
      body: formData,
    });

    if (!response.ok) {
      throw new Error("文件处理失败");
    }

    return await response.json();
  },

  // 评论分析
  analyzeComment: async (comments: string) => {
    const response = await fetch("http://localhost:8000/api/teach/comment", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ comments }),
    });

    if (!response.ok) {
      throw new Error("评论分析失败");
    }

    return await response.json();
  },
};

// 教师端API
export const teacherAPI = {
  // 获取概览数据 (暂时使用班级列表接口)
  getOverview: () => httpGet(API_ENDPOINTS.TEACHER.LIST_CLASS),

  // 获取班级列表
  getClasses: (params?: any) =>
    httpGet(API_ENDPOINTS.TEACHER.LIST_CLASS, params),

  // 获取课程列表 (暂时使用班级列表接口)
  getCourses: (params?: any) =>
    httpGet(API_ENDPOINTS.TEACHER.LIST_CLASS, params),

  // 获取学生列表 (使用班级成员接口)
  getStudents: (classId: number, allow: number = 1) =>
    httpGet(`${API_ENDPOINTS.TEACHER.ATTEND_LIST}/${classId}?allow=${allow}`),

  // 获取考试列表
  getExams: (classId: number) =>
    httpGet(`${API_ENDPOINTS.TEACHER.LIST_EXAM}?class_id=${classId}`),

  // 获取学习分析数据 (暂时使用建议列表接口)
  getAnalysis: (classId: number) =>
    httpGet(`${API_ENDPOINTS.TEACHER.LIST_ADVICE}?class_id=${classId}`),

  // 获取教学资源 (使用文件列表接口)
  getResources: (classId: number) =>
    httpGet(`${API_ENDPOINTS.TEACHER.LIST_FILE}?classId=${classId}`),

  // 创建班级
  createClass: (data: any) => httpGet(API_ENDPOINTS.TEACHER.CREATE_CLASS, data),

  // 删除班级
  deleteClass: (id: number) =>
    httpDelete(`${API_ENDPOINTS.TEACHER.DELETE_CLASS}/${id}`),

  // 同意学生入班申请
  allowStudent: (stuId: number, classId: number) =>
    httpGet(
      `${API_ENDPOINTS.TEACHER.ALLOW_STUDENT}?stuId=${stuId}&classId=${classId}`
    ),

  // 获取班级成员
  getAttendees: (classId: number, allow: number) =>
    httpGet(`${API_ENDPOINTS.TEACHER.ATTEND_LIST}/${classId}?allow=${allow}`),

  // 上传文件
  uploadFile: (file: File, onProgress?: (progress: number) => void) =>
    httpUpload(API_ENDPOINTS.TEACHER.UPLOAD_FILE, file, onProgress),

  // 添加课堂文件
  addFile: (data: any) => httpPost(API_ENDPOINTS.TEACHER.ADD_FILE, data),

  // 获取文件列表
  getFileList: (classId: number) =>
    httpGet(`${API_ENDPOINTS.TEACHER.LIST_FILE}?classId=${classId}`),

  // 发布文件
  publishFile: (fileId: number) =>
    httpPut(`${API_ENDPOINTS.TEACHER.PUBLISH_FILE}?fileId=${fileId}`),

  // 删除文件
  deleteFile: (fileId: number) =>
    httpPut(`${API_ENDPOINTS.TEACHER.DELETE_FILE}?fileId=${fileId}`),

  // 获取建议列表
  getAdviceList: (classId: number) =>
    httpGet(`${API_ENDPOINTS.TEACHER.LIST_ADVICE}?class_id=${classId}`),

  // 反馈建议
  feedbackAdvice: (data: any) =>
    httpPost(API_ENDPOINTS.TEACHER.FEEDBACK_ADVICE, data),

  // 添加考试
  addExam: (data: any) => httpPost(API_ENDPOINTS.TEACHER.ADD_EXAM, data),

  // 获取考试列表
  getExamList: (classId: number) =>
    httpGet(`${API_ENDPOINTS.TEACHER.LIST_EXAM}?class_id=${classId}`),
};

// 学生端API
export const studentAPI = {
  // 申请加入班级
  addToClass: (classId: number) =>
    httpGet(`${API_ENDPOINTS.STUDENT.ADD_CLASS}?classId=${classId}`),

  // 获取班级信息
  getClassInfo: (id: number) =>
    httpGet(`${API_ENDPOINTS.STUDENT.CLASS_INFO}/${id}`),

  // 获取课程列表 (暂时使用班级列表接口)
  getCourses: (params?: any) => httpGet(API_ENDPOINTS.STUDENT.COURSES, params),

  // 获取考试列表 (暂时使用班级考试接口)
  getExams: (params?: any) => httpGet(API_ENDPOINTS.STUDENT.EXAMS, params),

  // 获取学习资源 (使用文件接口)
  getResources: (classId: number) =>
    httpGet(`${API_ENDPOINTS.STUDENT.GET_FILE}/${classId}`),

  // 获取个人资料 (暂时使用用户信息接口)
  getProfile: () => httpGet(API_ENDPOINTS.AUTH.USER_INFO),

  // 上传文件
  uploadFile: (file: File, onProgress?: (progress: number) => void) =>
    httpUpload(API_ENDPOINTS.STUDENT.UPLOAD_FILE, file, onProgress),

  // 添加建议
  addAdvice: (data: any) => httpPost(API_ENDPOINTS.STUDENT.ADD_ADVICE, data),

  // 获取建议列表
  getAdviceList: (classId: number) =>
    httpGet(`${API_ENDPOINTS.STUDENT.LIST_ADVICE}?class_id=${classId}`),

  // 添加话题
  addTopic: (data: any) => httpPost(API_ENDPOINTS.STUDENT.ADD_TOPIC, data),

  // 获取话题列表
  getTopicList: (data: any) => httpGet(API_ENDPOINTS.STUDENT.LIST_TOPIC, data),

  // 删除话题
  deleteTopic: (topicId: number) =>
    httpGet(`${API_ENDPOINTS.STUDENT.DEL_TOPIC}?topic_id=${topicId}`),

  // 点赞话题
  likeTopic: (topicId: number) =>
    httpGet(`${API_ENDPOINTS.STUDENT.GOOD_TOPIC}?topic_id=${topicId}`),

  // 添加评论
  addComment: (data: any) => httpPost(API_ENDPOINTS.STUDENT.ADD_COMMENT, data),

  // 获取评论列表
  getCommentList: (topicId: number, page: number, size: number) =>
    httpGet(
      `${API_ENDPOINTS.STUDENT.LIST_COMMENT}?topic_id=${topicId}&page=${page}&size=${size}`
    ),

  // 删除评论
  deleteComment: (commentId: number) =>
    httpGet(`${API_ENDPOINTS.STUDENT.DEL_COMMENT}?comment_id=${commentId}`),
};

// 管理员API
export const adminAPI = {
  // 教师管理
  getTeachers: (params?: any) => httpGet(API_ENDPOINTS.ADMIN.TEACHERS, params),

  createTeacher: (data: any) => httpPost(API_ENDPOINTS.ADMIN.TEACHERS, data),

  updateTeacher: (id: string, data: any) =>
    httpPut(`${API_ENDPOINTS.ADMIN.TEACHERS}/${id}`, data),

  deleteTeacher: (id: string) =>
    httpDelete(`${API_ENDPOINTS.ADMIN.TEACHERS}/${id}`),

  // 学生管理
  getStudents: (params?: any) => httpGet(API_ENDPOINTS.ADMIN.STUDENTS, params),

  createStudent: (data: any) => httpPost(API_ENDPOINTS.ADMIN.STUDENTS, data),

  updateStudent: (id: string, data: any) =>
    httpPut(`${API_ENDPOINTS.ADMIN.STUDENTS}/${id}`, data),

  deleteStudent: (id: string) =>
    httpDelete(`${API_ENDPOINTS.ADMIN.STUDENTS}/${id}`),

  // 课程管理
  getCourses: (params?: any) => httpGet(API_ENDPOINTS.ADMIN.COURSES, params),

  createCourse: (data: any) => httpPost(API_ENDPOINTS.ADMIN.COURSES, data),

  updateCourse: (id: string, data: any) =>
    httpPut(`${API_ENDPOINTS.ADMIN.COURSES}/${id}`, data),

  deleteCourse: (id: string) =>
    httpDelete(`${API_ENDPOINTS.ADMIN.COURSES}/${id}`),

  // 系统设置
  getSettings: () => httpGet(API_ENDPOINTS.ADMIN.SETTINGS),

  updateSettings: (data: any) => httpPost(API_ENDPOINTS.ADMIN.SETTINGS, data),

  // 统计数据
  getStatistics: (params?: any) =>
    httpGet(API_ENDPOINTS.ADMIN.STATISTICS, params),
};

// 文件上传API
export const uploadAPI = {
  // 上传图片
  uploadImage: (file: File, onProgress?: (progress: number) => void) =>
    httpUpload(API_ENDPOINTS.UPLOAD.IMAGE, file, onProgress),

  // 上传文档
  uploadDocument: (file: File, onProgress?: (progress: number) => void) =>
    httpUpload(API_ENDPOINTS.UPLOAD.DOCUMENT, file, onProgress),

  // 通用文件上传
  uploadFile: (file: File, onProgress?: (progress: number) => void) =>
    httpUpload(API_ENDPOINTS.UPLOAD.FILE, file, onProgress),
};

// 考试相关API
export const examAPI = {
  // 获取试题列表
  getQuestions: (params?: any) => httpGet(API_ENDPOINTS.EXAM.LIST, params),

  // AI生成试题
  generateQuestions: (prompt: string) =>
    httpPost(API_ENDPOINTS.EXAM.AI_GENERATE, { prompt }),
};

// API健康检查
export const healthAPI = {
  // 检查API服务状态
  checkHealth: async () => {
    try {
      console.log("🔍 检查API服务状态...");
      const response = await httpGet("/api/health", {}, { useCache: false });

      console.log("✅ API服务正常:", response);
      return { status: "ok", data: response };
    } catch (error) {
      console.error("❌ API服务异常:", error);
      return { status: "error", error };
    }
  },

  // 检查认证服务
  checkAuth: async () => {
    try {
      console.log("🔍 检查认证服务...");
      const response = await authAPI.getUserInfo();

      if (response?.code === 0) {
        return { status: "authenticated", user: response.data };
      } else {
        return { status: "unauthenticated" };
      }
    } catch (error) {
      console.error("❌ 认证检查失败:", error);
      return { status: "error", error };
    }
  },

  // 批量健康检查
  checkAll: async () => {
    const results = await Promise.allSettled([
      healthAPI.checkHealth(),
      healthAPI.checkAuth(),
    ]);

    return {
      health:
        results[0].status === "fulfilled"
          ? results[0].value
          : { status: "error" },
      auth:
        results[1].status === "fulfilled"
          ? results[1].value
          : { status: "error" },
      timestamp: new Date().toISOString(),
    };
  },
};

// 导出所有API
export default {
  auth: authAPI,
  ai: aiAPI,
  teacher: teacherAPI,
  student: studentAPI,
  admin: adminAPI,
  upload: uploadAPI,
  exam: examAPI,
  health: healthAPI,
};
